const puppeteer = require('puppeteer');
const fs = require('fs');
const url = `https://movie.douban.com/explore#!type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20&page_start=0`;
// 休眠时间
const sleep = time => new Promise(resolve => setTimeout(resolve, time));

(async () => {
    console.log('start');
    const browser = await puppeteer.launch({
        args: ['--no-sandbox'],
        dumpio: false
    });
    const page = await browser.newPage();
    await page.goto(url, {
        waitUntil: 'networkidle2'
    });
    await page.setViewport({width:1920, height:1080});
    // 自适应页面宽高
    const documentSize = await page.evaluate(() => {
        return {
            width: document.documentElement.clientWidth,
            height : document.body.clientHeight,
        }
    });
    await page.setViewport({width:1920, height:documentSize.height});

    // await page.screenshot({path:"example.png", clip : {x:0, y:0, width:1920, height:documentSize.height}});

    await sleep(1500);
    console.log('等待1.5秒');
    // 首页
    // await page.screenshot({path: 'default.png'});

    const feedHandle = await page.$('.list');
    // 电影名和评分
    const res = await feedHandle.$$eval('.item', nodes => nodes.map(n =>  {
       return n.innerText;
    }));
    // console.log(res);
    // 获取电影图片
    const img = await feedHandle.$$eval('.cover-wp img', nodes => nodes.map(n => {
        return n.src;
    }));
    // console.log(img);

    const result = [];
    // 格式化数据
    for (let i=0; i<res.length; i++) {
        const _arr = res[i].split(" ");
        const title = _arr[0];
        const rate = _arr[1];
        const url = img[i];
        result.push({
            title,
            rate,
            url
        })
    }
    // 点击查看更多
    // const moreElement = await page.$('.more');
    // await moreElement.click();
    // await page.screenshot({path: 'example.png'});

    await browser.close();
    // console.log(result);
    /**
     * filename, 必选参数，文件名
     * data, 写入的数据，可以字符或一个Buffer对象
     * [options],flag,mode(权限),encoding
     * callback 读取文件后的回调函数，参数默认第一个err,第二个data 数据
     */
    fs.writeFile(__dirname + '/movie_list.json', JSON.stringify(result), {flag: 'a', encoding: 'utf-8'},  (err) => {
        if (err) {
            console.log(err)
        } else {
            console.log('存储成功')
        }
    });
    // 返回结果 或者存储到数据库
    // return result;
    // 通过进程发送数据
    process.send({result});
    process.exit(0)
})();